package com.imay.live.view;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;

import com.imay.live.R;


public class CircularImageView extends ImageView {
    private boolean hasBorder;
    private boolean hasSelector;
    /**
     * 是否选中
     */
    private boolean isSelected;
    /**
     * 边框宽度的像素
     */
    private int borderWidth;
    /**
     * 画布尺寸
     */
    private int canvasSize;
    /**
     * 笔划宽度
     */
    private int selectorStrokeWidth;

    /**
     * 对象用于实际的绘图
     */
    private BitmapShader shader;
    /**
     * Bitmap
     */
    private Bitmap image;// 此属性如何获取?
    /**
     * 选中和非选中 都会使用的画笔: 画内圆图画的画笔
     */

    /**
     * 设置CircularImageView的基本边框颜色 画笔: 没选中状态下, 外圆画笔
     */
    private Paint paintBorder;
    /**
     * 点击选中时使用此 画笔 绘制UI: 选中情况下, 外圆画笔
     */
    private Paint paintSelectorBorder;
    /**
     * 颜色过滤
     */
    private ColorFilter selectorFilter;
    /**
     * 透明圆环宽度
     */
    float widthAlpha;
    /**
     * 是否圆弧
     */
    private boolean isArc;

    private String string = "20万";

    public void setString(String text){
        if(TextUtils.isEmpty(text)){
            return;
        }
        string = text;
        invalidate();
    }

    public CircularImageView(Context context) {
        this(context, null);
    }

    public CircularImageView(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.circularImageViewStyle);
    }

    public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    /**
     * @param context
     * @param attrs
     * @param defStyle
     */
    private void init(Context context, AttributeSet attrs, int defStyle) {
        paintBorder = new Paint();
        paintBorder.setAntiAlias(true);
        paintSelectorBorder = new Paint();
        paintSelectorBorder.setAntiAlias(true);

        widthAlpha = 4 * context.getResources().getDisplayMetrics().density + 0.5f;

        //加载样式属性和设置它们的属性
        TypedArray attributes = context.obtainStyledAttributes(attrs,
                R.styleable.CircularImageView, defStyle, 0);// 获取属性列表

        //如果启用了边界和/或边境检查
        hasBorder = attributes.getBoolean(R.styleable.CircularImageView_border,
                false);
        hasSelector = attributes.getBoolean(
                R.styleable.CircularImageView_selector, false);

        isArc = attributes.getBoolean(R.styleable.CircularImageView_is_arc,false);

        //如果启用设置边界属性
        if (hasBorder) {// 默认(没点击选中时)情况
            int defaultBorderSize = (int) (2 * context.getResources()
                    .getDisplayMetrics().density + 0.5f);// 默认边界尺寸
            // 默认情况下, 外环宽度
            setBorderWidth(attributes.getDimensionPixelOffset(
                    R.styleable.CircularImageView_border_width,
                    defaultBorderSize));
            // 获取颜色
            setBorderColor(attributes.getColor(
                    R.styleable.CircularImageView_border_color, Color.WHITE));
        }

        if (hasSelector) {// 点击选中时情况
            int defaultSelectorSize = (int) (2 * context.getResources()
                    .getDisplayMetrics().density + 0.5f);
            setSelectorColor(attributes.getColor(
                    R.styleable.CircularImageView_selector_color,
                    Color.TRANSPARENT));// 透明度
            // 默认选择大小 外环宽度
            setSelectorStrokeWidth(attributes.getDimensionPixelOffset(
                    R.styleable.CircularImageView_selector_stroke_width,
                    defaultSelectorSize));
            // 边框颜色
            setSelectorStrokeColor(attributes.getColor(
                    R.styleable.CircularImageView_selector_stroke_color,
                    Color.BLUE));
        }

        //是否添加阴影
        if (attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
            addShadow();

        attributes.recycle();// 为了属性保持一致, 需要调用此方法
    }

    /**
     * 设置CircularImageView边框宽度的像素
     *
     * @param borderWidth
     */
    public void setBorderWidth(int borderWidth) {
        this.borderWidth = borderWidth;
        this.requestLayout();
        this.invalidate();
    }

    /**
     * 设置CircularImageView的基本边框颜色
     *
     * @param borderColor
     */
    public void setBorderColor(int borderColor) {
        if (paintBorder != null)
            paintBorder.setColor(borderColor);
        this.invalidate();
    }

    /**
     * 设置透明度---> 颜色过滤法
     *
     * @param selectorColor
     */
    public void setSelectorColor(int selectorColor) {
        this.selectorFilter = new PorterDuffColorFilter(selectorColor,
                PorterDuff.Mode.SRC_ATOP);
        this.invalidate();
    }

    /**
     * 设置笔划宽度 ---> 在单击事件选择器时启用
     *
     * @param selectorStrokeWidth
     */
    public void setSelectorStrokeWidth(int selectorStrokeWidth) {
        this.selectorStrokeWidth = selectorStrokeWidth;
        this.requestLayout();
        this.invalidate();
    }

    /**
     * 设置 画笔颜色 ---> 在单击事件选择器时启用
     */
    public void setSelectorStrokeColor(int selectorStrokeColor) {
        if (paintSelectorBorder != null)
            paintSelectorBorder.setColor(selectorStrokeColor);
        this.invalidate();
    }

    /**
     * 添加阴影
     */
    public void addShadow() {
        setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);// 硬件加速
        paintBorder.setShadowLayer(4.0f, 0.0f, 0.0f, Color.BLACK);// 阴影
    }

    @Override
    public void onDraw(Canvas canvas) {
        if (image == null)
            return;

        if (image.getHeight() == 0 || image.getWidth() == 0)
            return;

        //旧画布尺寸
        int oldCanvasSize = canvasSize;

        canvasSize = canvas.getWidth();// 画布宽度
        if (canvas.getHeight() < canvasSize)// 画布高度
            canvasSize = canvas.getHeight();// 取宽高中较小的值

        //if (oldCanvasSize != canvasSize)// 两者不相等
        refreshBitmapShader();

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        //设置着色器
        paint.setShader(shader);

        //边框宽度
        int outerWidth = 0;

        //画布中心
        int center = canvasSize / 2;

        if (hasSelector && isSelected) { // 如果选中
            outerWidth = selectorStrokeWidth;// 外环宽度: 实际是两个圆叠一起看上去像外环
            center = (canvasSize - (outerWidth * 2)) / 2;// 减去两边边框后得到的中心

            paint.setColorFilter(selectorFilter);// 设置过滤器
            // 画一个圆 1, 2参数为圆心坐标, 3参为半径, 4参为画笔
            canvas.drawCircle(center + outerWidth, center + outerWidth,
                    ((canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f,
                    paintSelectorBorder);
        } else if (hasBorder) {
            // 如果没选中, 并且有边框. 重画边框并去掉过滤器
            outerWidth = borderWidth;
            center = (canvasSize - (outerWidth * 2)) / 2;

            paint.setColorFilter(null);// 去掉过滤器
            canvas.drawCircle(center + outerWidth, center + outerWidth,
                    ((canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f,
                    paintBorder);
        } else
            paint.setColorFilter(null);

        canvas.drawCircle(center + outerWidth, center + outerWidth,
                ((canvasSize - (outerWidth * 2)) / 2) - 4.0f, paint);

        if(isArc){
            float banjing = ((canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f;
            Paint mPaint2 = new Paint();
            mPaint2.setColor(Color.parseColor("#70000000"));
            mPaint2.setAntiAlias(true);
            RectF rect = new RectF(0, 0, center+banjing+2, center+banjing+2);
            canvas.drawArc(rect, //弧线所使用的矩形区域大小
                    30,  //开始角度
                    120, //扫过的角度
                    false, //是否使用中心
                    mPaint2);

            Paint mPaint = new Paint();
            mPaint.setColor(Color.WHITE);
            mPaint.setTextSize(getResources().getDimension(R.dimen.text_size_1x));
            mPaint.setAntiAlias(true);
            float cy = center + outerWidth + (banjing*5/6);
            float cx = center;

            float strWidth = mPaint.measureText(string);
            canvas.drawText(string,cx - strWidth/2,cy,mPaint);
        }
    }

    /**
     * 点击事件分发
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (!this.isClickable()) {
            this.isSelected = false;
            return super.onTouchEvent(event);
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                this.isSelected = true;// 选中
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_SCROLL:
            case MotionEvent.ACTION_OUTSIDE:
            case MotionEvent.ACTION_CANCEL:
                this.isSelected = false;// 非选中
                break;
        }

        this.invalidate();//重画当前 View
        return super.dispatchTouchEvent(event);// true: 自己消费点击事件, 不再分发给子View
    }

    @Override
    public void invalidate(Rect dirty) {
        super.invalidate(dirty);
        image = drawableToBitmap(getDrawable());
//        if (shader != null || canvasSize > 0)
//            refreshBitmapShader();
    }

    @Override
    public void invalidate(int l, int t, int r, int b) {
        super.invalidate(l, t, r, b);
        image = drawableToBitmap(getDrawable());
//        if (shader != null || canvasSize > 0)
//            refreshBitmapShader();
    }

    /**
     * 调用此方法再调用 onDraw 方法: image已经赋值
     */
    @Override
    public void invalidate() {
        super.invalidate();
        image = drawableToBitmap(getDrawable());// getDrawable 获取视图的 图片资源
//        if (shader != null || canvasSize > 0)
//            refreshBitmapShader();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    /**
     * 测量宽
     */
    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);// 获取模式
        int specSize = MeasureSpec.getSize(measureSpec);// 获取原尺寸

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            result = specSize;
        } else {
            result = canvasSize;
        }

        return result;
    }

    /**
     * 测量高
     */
    private int measureHeight(int measureSpecHeight) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpecHeight);// 获取模式
        int specSize = MeasureSpec.getSize(measureSpecHeight);// 获取原尺寸

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            result = specSize;
        } else {
            result = canvasSize;
        }
        return (result + 2);// 结果加 2 个像素返回
    }

    /**
     * Drawable 转换为 Bitmap
     *
     * @param drawable
     * @return
     */
    public Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable == null) {
            return null;
        } else if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }

    public void refreshBitmapShader() {
        Matrix m = new Matrix();
        final int width = image.getWidth();
        final int height = image.getHeight();
        int w;
        if(width< height){
            w = width;
            final float sx = canvasSize  / (float)width;
            m.setScale(sx, sx,width/2,height/2);
        }else{
            w = height;
            final float sy = canvasSize / (float)height;
            m.setScale(sy, sy,width/2,height/2);
        }

        Bitmap b = Bitmap.createBitmap(image, 0, 0, w, w, m, false);
        shader = new BitmapShader(b, Shader.TileMode.CLAMP,
                Shader.TileMode.CLAMP);
    }

    /**
     * 是否选中本View
     */
    @Override
    public boolean isSelected() {
        return this.isSelected;
    }
}